package com.faker.dao;

import com.alibaba.druid.support.json.JSONUtils;
import com.faker.entity.SysConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Repository
@Slf4j
public class ConfigurationDao {
    @Resource
    JdbcTemplate jdbcTemplate;


    public int saveConfiguration(SysConfiguration sysConfiguration) {
        StringBuffer sb = new StringBuffer();
        sb.append(" replace into sys_configuration (connection_id, global_table_data, active_names, table_data_array)     ");
        sb.append(" values (?, ?, ?, ?)                                                                                   ");
        int update = jdbcTemplate.update(sb.toString(), sysConfiguration.getConnectionId(), JSONUtils.toJSONString(sysConfiguration.getGlobalTableData()), JSONUtils.toJSONString(sysConfiguration.getActiveNames()), JSONUtils.toJSONString(sysConfiguration.getTableDataArray()));
        return update;
    }

    public SysConfiguration queryConfiguration(Long connectionId) {
        SysConfiguration sysConfiguration = new SysConfiguration();
        StringBuffer sb = new StringBuffer();
        sb.append(" select connection_id     as connectionId,      ");
        sb.append("        global_table_data as globalTableData,   ");
        sb.append("        active_names      as activeNames,       ");
        sb.append("        table_data_array  as tableDataArray     ");
        sb.append(" from sys_configuration                         ");
        sb.append(" where connection_id = ?                        ");

        List<Map<String, Object>> list = jdbcTemplate.queryForList(sb.toString(), connectionId);
        if (list.size() > 0) {
            Map<String, Object> map = list.get(0);
            String globalTableDataStr = map.get("globalTableData").toString();
            String activeNamesStr = map.get("activeNames").toString();
            String tableDataArrayStr = map.get("tableDataArray").toString();
            sysConfiguration.setConnectionId(connectionId);
            if (globalTableDataStr != null && !globalTableDataStr.equals("")) {
                sysConfiguration.setGlobalTableData((List) JSONUtils.parse(globalTableDataStr));
            }
            if (activeNamesStr != null && !activeNamesStr.equals("")) {
                sysConfiguration.setActiveNames((List) JSONUtils.parse(activeNamesStr));
            }
            if (tableDataArrayStr != null && !tableDataArrayStr.equals("")) {
                sysConfiguration.setTableDataArray((List) JSONUtils.parse(tableDataArrayStr));
            }
        } else {
            sysConfiguration.setConnectionId(connectionId);
        }
        return sysConfiguration;
    }


}
